//
//  SpaceTableViewController.m
//  chatchatchat
//
//  Created by 小灰灰的pro on 16/3/25.
//  Copyright © 2016年 小灰灰. All rights reserved.
//

#import "SpaceTableViewController.h"
#import "SpaceTableViewCell.h"
#import "SpaceFirstTableViewCell.h"
#import "WriteTextViewController.h"
#import <AVOSCloud/AVOSCloud.h>
#import "MJRefresh.h"
@interface SpaceTableViewController ()

@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSMutableArray *timeArray;
@property (nonatomic,strong)NSMutableArray *likeArray;

@end

@implementation SpaceTableViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = [[NSMutableArray alloc] init];
    self.timeArray = [[NSMutableArray alloc] init];
    self.likeArray = [[NSMutableArray alloc] init];
    [self.tableView registerClass:[SpaceTableViewCell class] forCellReuseIdentifier:@"SpaceCell"];
    [self.tableView registerClass:[SpaceFirstTableViewCell class] forCellReuseIdentifier:@"SpaceFirstCell"];
    //设置标题
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((self.view.bounds.size.width - 50) / 2, 7, 50, 50)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:18.0];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.text = @"时空";
    self.navigationItem.titleView = label;
    //左item
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发现" style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItemAction)];
    //右item
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"PayScanicon@2x"] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonItemAction)];
    //数据
    [self handleData];
    [self setupRefresh];
}
/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉刷新";
    self.tableView.headerReleaseToRefreshText = @"松开刷新";
    self.tableView.headerRefreshingText = @"正在刷新...";
    
}

- (void)headerRereshing{
    
    AVQuery *query = [AVQuery queryWithClassName:@"TodoFolder"];
    //按时间将序排序
    [query orderByDescending:@"createdAt"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        NSArray<AVObject *> *priorityEqualsZeroTodos = objects;
        self.dataArray = [[NSMutableArray alloc] init];
        self.timeArray = [[NSMutableArray alloc] init];
        self.likeArray = [[NSMutableArray alloc] init];
        for (AVObject *obj in priorityEqualsZeroTodos) {
            [self.dataArray addObject:[obj valueForKey:@"context"]];
            NSDate *dateTime = [obj valueForKey:@"createdAt"];
            [self.likeArray addObject:[obj valueForKey:@"like"]];
            //当前时间
            NSDate *nowDate = [NSDate date];
            //时间间隔按秒计算,我们所在的区是东八区,转化成秒8*60*60
            NSDate *nowDate2 = [nowDate dateByAddingTimeInterval:8*60*60];
            NSDate *date = [dateTime dateByAddingTimeInterval:8*60*60];
            //换算成多少时间之前
            NSTimeInterval time1 = [nowDate2 timeIntervalSinceDate:date];
            if (time1 < 60 && time1 > 0) {
                NSString *timeString = [NSString stringWithFormat:@"%.1f",time1];
                NSString *timeStr = [timeString stringByAppendingString:@"秒之前"];
                [self.timeArray addObject:timeStr];
            }else if(time1 < 3600 && time1 >= 60){
                NSString *timeString = [NSString stringWithFormat:@"%.1f",time1/60];
                NSString *timeStr = [timeString stringByAppendingString:@"分钟之前"];
                [self.timeArray addObject:timeStr];
            }else if(time1 < 3600*24 && time1 >= 3600){
                NSString *timeString = [NSString stringWithFormat:@"%.1f",time1/3600];
                NSString *timeStr = [timeString stringByAppendingString:@"小时之前"];
                [self.timeArray addObject:timeStr];
            }else{
                NSString *timeString = [NSString stringWithFormat:@"%.1f",time1/3600/24];
                NSString *timeStr = [timeString stringByAppendingString:@"天之前"];
                [self.timeArray addObject:timeStr];
            }
            
        }
        [self.tableView reloadData];
    }];
     [self.tableView headerEndRefreshing];
}

- (void)handleData{
    AVQuery *query = [AVQuery queryWithClassName:@"TodoFolder"];
    //按时间将序排序
    [query orderByDescending:@"createdAt"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        NSArray<AVObject *> *priorityEqualsZeroTodos = objects;
        for (AVObject *obj in priorityEqualsZeroTodos) {
            [self.dataArray addObject:[obj valueForKey:@"context"]];
            [self.likeArray addObject:[obj valueForKey:@"like"]];
            NSDate *dateTime = [obj valueForKey:@"createdAt"];
            //当前时间
            NSDate *nowDate = [NSDate date];
            //时间间隔按秒计算,我们所在的区是东八区,转化成秒8*60*60
            NSDate *nowDate2 = [nowDate dateByAddingTimeInterval:8*60*60];
            NSDate *date = [dateTime dateByAddingTimeInterval:8*60*60];
            //换算成多少时间之前
            NSTimeInterval time1 = [nowDate2 timeIntervalSinceDate:date];
            if (time1 < 60 && time1 > 0) {
                NSString *timeString = [NSString stringWithFormat:@"%.1f",time1];
                NSString *timeStr = [timeString stringByAppendingString:@"秒之前"];
                [self.timeArray addObject:timeStr];
            }else if(time1 < 3600 && time1 >= 60){
                NSString *timeString = [NSString stringWithFormat:@"%.1f",time1/60];
                NSString *timeStr = [timeString stringByAppendingString:@"分钟之前"];
                [self.timeArray addObject:timeStr];
            }else if(time1 < 3600*24 && time1 >= 3600){
                NSString *timeString = [NSString stringWithFormat:@"%.1f",time1/3600];
                NSString *timeStr = [timeString stringByAppendingString:@"小时之前"];
                [self.timeArray addObject:timeStr];
            }else{
                NSString *timeString = [NSString stringWithFormat:@"%.1f",time1/3600/24];
                NSString *timeStr = [timeString stringByAppendingString:@"天之前"];
                [self.timeArray addObject:timeStr];
            }
            
        }
        [self.tableView reloadData];
    }];
}

- (void)rightBarButtonItemAction{
    WriteTextViewController *writeVC = [[WriteTextViewController alloc] init];
    [self presentViewController:writeVC animated:YES completion:nil];
}

- (void)leftBarButtonItemAction {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else{
        return self.dataArray.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        SpaceFirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SpaceFirstCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        SpaceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SpaceCell" forIndexPath:indexPath];
        //重新定义label的高度
        cell.contextLabel.frame = CGRectMake(CGRectGetMinX(cell.contextLabel.frame), CGRectGetMinY(cell.contextLabel.frame), CGRectGetWidth(cell.contextLabel.frame), [self contentHeight:self.dataArray[indexPath.row]]);
        cell.timeLabel.frame = CGRectMake(CGRectGetMinX(cell.timeLabel.frame), CGRectGetMaxY(cell.contextLabel.frame), CGRectGetWidth(cell.timeLabel.frame), CGRectGetHeight(cell.timeLabel.frame));
        cell.likeLabel.frame = CGRectMake(CGRectGetMinX(cell.likeLabel.frame), CGRectGetMaxY(cell.contextLabel.frame), CGRectGetWidth(cell.likeLabel.frame), CGRectGetHeight(cell.likeLabel.frame));
        cell.like_countLabel.frame = CGRectMake(CGRectGetMinX(cell.like_countLabel.frame), CGRectGetMaxY(cell.contextLabel.frame), CGRectGetWidth(cell.like_countLabel.frame), CGRectGetHeight(cell.like_countLabel.frame));
        cell.likeButton.frame = CGRectMake(CGRectGetMinX(cell.likeButton.frame), CGRectGetMaxY(cell.contextLabel.frame), CGRectGetWidth(cell.likeButton.frame), CGRectGetHeight(cell.likeButton.frame));
        
        cell.contextLabel.text = self.dataArray[indexPath.row];
        cell.timeLabel.text = self.timeArray[indexPath.row];
        cell.like_countLabel.text = [NSString stringWithFormat:@"%@",self.likeArray[indexPath.row]];
        //点赞
        [cell.likeButton addTarget:self action:@selector(likeButtonAction) forControlEvents:UIControlEventTouchUpInside];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
- (void)likeButtonAction{
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 230;
    }
    return [self contentHeight:self.dataArray[indexPath.row]] + 70;
}
//自适应高度
- (CGFloat)contentHeight:(NSString *)textString{
    CGRect temp = [textString boundingRectWithSize:CGSizeMake(self.tableView.frame.size.width, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]} context:nil];
    return temp.size.height + 10;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
